<template>
  <div class="mgmt-user">
    <div class="operate">
      <el-button type="primary" @click="openModel('add')">新建</el-button>
    </div>
    <div style="height: calc(100% - 92px)">
      <UnTable 
          :tableData="tableData"
          :tableOption="tableOption"
          @pageChange="pageChange"
        >
          <template #action="{scope}">
                <el-button size="small" type="primary" @click="openModel('update', scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="delUser(scope.$index, scope.row)">删除</el-button>
          </template>
        </UnTable>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="添加用户" width="30%">
    <div class="userForm">
      <el-form :model="form" label-width="120px" label-position="top" ref="ruleFormRef" :rules="rules">
        <el-form-item prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input v-model="form.pwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
            <el-option label="保密" value="保密" />
          </el-select>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="tel">
          <el-input v-model="form.tel" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, computed } from 'vue'
import { getUser, addUser, delUserApi } from '@/api/mgmtUser' //api/后面不能大写Mgmt
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs' // ES 2015
import {TableOption}  from '@/class/table.js'
import UnTable from '@/components/UnTable/index.vue'
function useTableHooks(){
  const table =ref({
    tableColumn: [
      { label: '用户姓名', prop: 'name' },
      { label: '用户密码', prop: 'pwd'},
      { label: '用户性别', prop: 'gender'},
      { label: '邮箱', prop: 'email'},
      { label: '联系方式', prop: 'tel' },
      {  label: '创建时间', prop: 'create_time'}
    ]
  })
  const tableOption = ref(new TableOption(table.value))
  const pageChange = async (val) => { 
    if(val.type==='currentPage'){
      tableOption.value.pageNum=val.pageNum
    }else{
      tableOption.value.pageSize=val.pageSize
      tableOption.value.pageNum=val.pageNum
    }
    initData()
  }
  return {tableOption,pageChange}
}
const {tableOption,pageChange} = useTableHooks()
const tableData = ref([])
const initData = async () => {
  let params = {
    pageSize: tableOption.value.pageSize,
    pageNum:tableOption.value.pageNum
  }
  const res = await getUser(params)
  if (res.code === 200) {
    tableData.value = res.data.list
    tableOption.value.total = res.data.total
  }
}
//删除用户
const delUser = (index, row) => {
  ElMessageBox.confirm(`是否要删除账号${row.name}?`, '确认删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await delUserApi({ id: row.id })
    if (res.code == 200) {
      ElMessage({ message: '删除成功', type: 'success' })
      initData()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

//添加用户
const dialogVisible = ref(false)
let form = reactive({
  name: '',
  pwd: '',
  gender: '',
  email: '',
  tel: ''
})
const rules = reactive({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { required: true, pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,16}$/, message: '2到16位(字母，汉字)', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { required: true, pattern: /^[a-zA-Z0-9]{4,16}$/, message: '4到16位(字母，数字)', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择角色', trigger: 'change' }],
  email: [
    { required: true, message: '请输入正确邮箱', trigger: 'blur' },
    {
      required: true,
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '请输入正确邮箱',
      trigger: 'blur'
    }
  ],
  tel: [
    { required: true, message: '手机号必填', trigger: 'blur' },
    { required: true, pattern: /^1[345789]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }
  ]
})
const ruleFormRef = ref(null)
const openModel = (msg, row) => {
  dialogVisible.value = true
  if (msg === 'update') {
    //返显信息
    form.name = row.name
    form.pwd = row.pwd
    form.gender = row.gender
    form.email = row.email
    form.tel = row.tel
    form.id = row.id
  } else {
    form.name = ''
    form.pwd = ''
    form.gender = ''
    form.email = ''
    form.tel = ''
    form.id = null
  }
}
// 添加 和 更新
const submit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      dialogVisible.value = false
      addUser(form).then((res) => {
        if (res.code == 200) {
          if (form.id) {
            ElMessage({ message: '更新成功', type: 'success' })
          } else {
            ElMessage({ message: '添加成功', type: 'success' })
          }
          initData()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
// 时间戳转成日期
const formats2 = (time) => {
  //time 多一个undefind
  return dayjs(time * 1).format('YYYY-MM-DD HH:mm:ss') //当前日期
}
const initAvatra = (value) => {
  let color = setColor()
  let name = value.name[0]
  return setLogo(color, name)
}
// 设置二维吗中间logo
const setLogo = (color, name) => {
  var canvas = document.createElement('canvas')
  canvas.width = 100
  canvas.height = 100
  var ctx = canvas.getContext('2d')
  ctx.beginPath()
  ctx.arc(50, 50, 50, 0, 2 * Math.PI)
  ctx.closePath()
  ctx.stroke()
  // 背景色
  ctx.fillStyle = color // 圆的填充颜色
  ctx.fill()
  var text = name
  ctx.font = '30px Arial' // 字体样式
  ctx.fillStyle = 'white' // 字体颜色
  ctx.textAlign = 'center' // 文字水平居中
  ctx.textBaseline = 'middle' // 文字垂直居中
  ctx.fillText(text, 50, 50)
  const base64PNG = canvas.toDataURL('image/png')
  return base64PNG
}
const setColor = () => {
  var letters = '0123456789ABCDEF'
  var color = '#'
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)]
  }
  return color
}
onMounted(() => {
  let a = 's'
  let b = 'as'
  initData()
})
</script>
<style lang="scss" scoped>
.box-card {
  height: 100%;
}

.mgmt-user {
  height: 100%;
  padding: 20px;

  .operate {
    margin-bottom: 20px;
  }
}

.userForm {
  .el-select {
    width: 100%;
  }
}
</style>
